package main

import "fmt"
import (
	"github.com/petermattis/goid"
	"time"
)

type EventLoop struct {
	id   int64
	task chan func()
}

func (evloop *EventLoop) Loop() {

	//todo timer

	//todo task
L:
	for {
		select {
		case t := <-evloop.task:
			t()
		default:
			break L
		}
	}
}

func (evloop *EventLoop) runInLoop(f func())  {
	if evloop.id == goid.Get() {
		f()
	} else{
		evloop.QueueTask(func() {
			evloop.runInLoop(f)
		})
	}
}

func (evloop *EventLoop) RunAfter(d time.Duration, f func()) {
	evloop.runInLoop(func() {
		time.AfterFunc(d,f)
	})
}



func (evloop *EventLoop) QueueTask(t func()) {
	evloop.task <- t
}

func CreateMainEventLoop() EventLoop {
	ch := make(chan func(), 200)
	rt := EventLoop{1, ch}
	rt.id = goid.Get()
	return rt
}

func CreateGoEventLoop() EventLoop {
	ch := make(chan func(), 200)
	rt := EventLoop{1, ch}
	initCh := make(chan int)
	go func() {
		rt.id = goid.Get()
		initCh <- 1
		rt.Loop()
	}()
	<-initCh
	close(initCh)
	return rt
}

func main() {

	fmt.Println(goid.Get())
	ev := CreateMainEventLoop()
	ev.QueueTask(func() {
		fmt.Println("hello1")
	})
	ev.QueueTask(func() {
		fmt.Println("hello2")
	})
	ev.Loop()
}
